package com.platform.mvc.user;

import com.alibaba.fastjson.JSON;
import com.application.common.Constant;
import com.application.common.parser.AbstractParser;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.platform.annotation.Table;
import com.platform.mvc.base.BaseModel;
import com.platform.mvc.usergroup.UserGroup;
import com.platform.plugin.ParamInitPlugin;
import com.platform.tools.ToolCache;
import org.apache.commons.codec.digest.DigestUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Table(tableName = "pt_user", pkName = "id")
public class User extends BaseModel<User> {
    public static final User dao = new User().dao();

    /**
     * sqlId : platform.user.splitPageSelect
     * 描述：分页Select
     */
    public static final String sqlId_splitPageSelect = "platform.user.splitPageSelect";

    /**
     * sqlId : platform.user.splitPageFrom
     * 描述：分页from
     */
    public static final String sqlId_splitPageFrom = "platform.user.splitPageFrom";

    /**
     * sqlId : platform.user.paging
     * 描述：查询所有用户
     */
    public static final String sqlId_paging = "platform.user.paging";

    public static final String column_ids = "id";
    public static final String column_username = "username";
    public static final String column_password = "password";
    public static final String column_status = "status";
    public static final String column_roleId = "role_id";

    public String getRoleId(){
        return get(column_roleId);
    }

    public Integer getId() {
        return get("id");
    }

    public void setId(Integer id) {
        set("id", id);
    }

    public String getUsername() {
        return get("username");
    }

    public void setUsername(String username) {
        set("username", username);
    }

    public String getPassword() {
        return get("password");
    }

    public void setPassword(String password) {
        set("password", password);
    }

    public String getStatus() {
        return get("status");
    }

    public void setStatus(String status) {
        set("status", status);
    }

    public String getName(){
        return getStr("name");
    }

    public void setName(String name){
        set("name", name);
    }

    public Integer getRefereeUserid() {
        return get("referee_userid");
    }

    public void setRefereeUserid(Integer referee_userid) {
        set("referee_userid", referee_userid);
    }

    public String getSecretkey() {
        return "2017";
    }

    public boolean updateMobile(String old, String newMobile) {
        return Db.update("update pt_user set mobile = ?, update_time = now() where id = ?",
                newMobile, old) > 0;
    }

    public boolean updateAlternative(User user) {
        boolean f = Db.update(getSqlByBeetl("platform.user.updateAlternative", user.getAttrs())) > 0;
        if (f) {
            Object id = user.get("id");
            if(id instanceof Integer){
                cacheRemove(user.getId());
            } else {
                cacheRemove(id.toString());
            }
        }
        return f;
    }


    public User getModelByMap(String password, Map<String, String> paramMap) {
        User user = new User();
        Map<String, Class<?>> columnTypeMap = getTable().getColumnTypeMap();

        paramMap.keySet().forEach(k -> {
            if (columnTypeMap.containsKey(k)) {
                String val = paramMap.get(k);

                String cName = columnTypeMap.get(k).getSimpleName() + "Parser";
                try {
                    AbstractParser o = (AbstractParser) Class.forName("com.application.common.parser." + cName)
                            .newInstance();

                    Object obj = o.parse(val);
                    user.set(k, obj);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
       /*     user.set(k, paramMap.get(k));}});
*/
        if (StrKit.notBlank(user.getStatus()) && !"1".equals(user.getStatus())) {
            user.setStatus("0");
        }

        if(user.get("gift") != null && StrKit.isBlank(user.get("gift").toString())){
            user.set("gift", 0);
        }

        if(user.get("money") != null && StrKit.isBlank(user.get("money").toString())){
            user.set("money", 0);
        }
        if (StrKit.notBlank(password)) {
            user.setPassword(DigestUtils.md5Hex(password));
        }
        return user;
    }

    /**
     * 添加或者更新缓存
     */
    public static User cacheAdd(String id) {
        User user = User.dao.findById(id);
        if (user != null) {
            //权限以角色为单位
            List<UserGroup> ugList = new ArrayList<>();
            user.put("ugList", ugList);
//            user.remove(User.column_password);
//            user.remove("pay_pass");
            ToolCache.set(ParamInitPlugin.cacheStart_user + id, user);
            ToolCache.set(ParamInitPlugin.cacheStart_user + user.getStr("username"), user);
        }
        return user;
    }

    public static User cacheAdd(Integer id) {
        return cacheAdd(String.valueOf(id.intValue()));
    }

    /**
     * 删除缓存
     */
    public static void cacheRemove(String id) {
        User user = User.dao.findById(id);
        if (user != null) {
            ToolCache.remove(ParamInitPlugin.cacheStart_user + id);
            ToolCache.remove(ParamInitPlugin.cacheStart_user + user.getStr("username"));
        }
    }

    public static void cacheRemove(Integer id) {
        cacheRemove(String.valueOf(id));
    }

    /**
     * 获取缓存
     *
     * @param ids
     * @return
     */
    public static User cacheGetByUserId(String id) {
        User user = ToolCache.get(ParamInitPlugin.cacheStart_user + id);
        if (user == null) {
            user = User.dao.findById(id);
            if (user != null) {
                cacheAdd(id);
            }
        }
        return user;
    }

    public static User cacheGetByUserId(Integer id) {
        return cacheGetByUserId(id.toString());
    }

    public static User getInfo(User user){
        //加入用户资料信息，如好友粉丝数
        /*user.put("friends_num", Db.queryLong(Friends.TYPE3, user.getId(), user.getId()));
        user.put("fans_num", Db.queryLong(Friends.TYPE2, user.getId()));
        user.put("attention_num", Db.queryLong(Friends.TYPE1, user.getId()));

        //获取用户等级及下一级所需经验值。
        int point = user.getInt("point");
        String levelName = "";
        int remainPoint = -1;
        List<DictValue> valueList = DictValue.dao.findByType(DictValue.type_userLevel);
        for (int i = 0; i < valueList.size(); i++) {
            DictValue value = valueList.get(i);
            int p = Integer.parseInt(value.getValue());
            if(point < p){
                levelName = value.getName();
                remainPoint = Integer.parseInt(valueList.get(i+1).getValue()) - point;
                break;
            }
        }
        user.put("level_name", levelName);
        user.put("remain_point", remainPoint);

        //获取用户兴趣爱好列表
        String hobby = user.get("hobby");
        List<String> hobbyList = new ArrayList<>();
        user.put("hobby_list", hobbyList);
        if (StrKit.notBlank(hobby)) {
            valueList = DictValue.dao.findByType(DictValue.type_userHobby);
            for (String s : hobby.split(",")) {
                hobbyList.addAll(valueList.stream().filter(value -> value.getCode().equals(s)).map(DictValue::getValue).collect(Collectors.toList()));
            }
        }*/
        return user;
    }


    public static User updateInfo(User user){
        user.set("login_num", user.getInt("login_num") + 1)
                .set("login_at", new Date())
                .update();
        //user.set("level", User.getLevel(user.getInt("point"))).update();
//.set("point", user.getInt("point") + 1)
        cacheRemove(user.getId());
        cacheAdd(user.getId());
        return user;
    }


    /*
    创建用户，同步环信账号
     */
    public static void saveInfo(User user) {
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                boolean $f = user.save();
//                EasemobHelper.createUser(user.getId().toString());
                user.set("chat_id", user.getId());
                user.update();
                System.out.println("###########create user:"+ JSON.toJSONString(user));
                return $f;
            }
        });

    }


    public User findByUsername(String username) {
        User user = User.dao.findFirst("select * from pt_user where username = ?", username);
        return user;
    }

    public void updatePoint(int userid, int value) {
        User user = findById(userid);
        user.set("point", user.getInt("point") + value).update();
        cacheRemove(userid);
    }

    public static boolean isVip(User user){
        if(Constant.group_vip.equalsIgnoreCase(user.getRoleId())){
            if (user.getDate("role_date") != null) {
                long role_date = user.getDate("role_date").getTime();
                return System.currentTimeMillis() < role_date;
            }
            return true;
        }
        return false;
    }

    /*
    根据手机号模糊查询
     */
    public List<User> queryByNo(String keyword) {
        String sql = "select id, name, username from " + getTableName() +
                " where instr(username, ?) >0 or instr(mobile, ?) >0 or instr(name, ?) >0 or id = ? limit 10 ";
        return find(sql, keyword, keyword, keyword, keyword);
    }

    public User findByOpenid(String openid) {
        return findFirst("select * from pt_user where openid =?", openid);
    }
}
